package org.snusmumr.android.media;

import java.util.Formatter;

import org.snusmumr.android.media.bean.ItemModel;
import org.snusmumr.android.media.data.DatabaseProvider;
import org.snusmumr.android.media.data.DatabaseProvider.DatabaseMode;
import org.snusmumr.android.media.dialog.ItemDialog;
import org.snusmumr.android.media.dialog.ItemDialog.ItemDialogListener;
import org.snusmumr.android.media.util.Utils;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class CategoryTab extends ListActivity {
	private ItemDialog addCategoryDlg;
	private DatabaseProvider dbProvider;
	private SimpleCursorAdapter adapter;
	
	
	private ItemDialogListener catedoryDlgListener = new ItemDialogListener() {
		@Override
		public void onOk(ItemModel<String> result) {
			if(result != null) {
				if(result.getId() == null)
					addItem(result);
				else
					updateItem(result);
			}
			
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		dbProvider = DatabaseProvider.getInstance(this);
        
		registerForContextMenu(getListView());
	}
	
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		Cursor c = (Cursor) adapter.getItem(position);
		String listItemName = c.getString(1);
        
        Intent intent = new Intent(CategoryTab.this, MediaList.class);
        intent.putExtra(Constants.KEY_PARENT_ID, id);
        intent.putExtra(Constants.KEY_PARENT_NAME, listItemName);
        intent.putExtra(Constants.KEY_PARENT_TYPE, MediaList.ParentType.Category);
		startActivity(intent);
	}


	@Override
	protected void onPause() {
		super.onPause();
		Utils.closeCursor(adapter);
		dbProvider.close();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		loadData();
	}

	private void loadData() {
		Cursor cursor = dbProvider.getDatabase(DatabaseMode.Read).query(Constants.DB_TABLE_CATEGORY, 
				Constants.DB_COLUMNS_CATEGORY, 
				null, null, null, null, "name asc");
		startManagingCursor(cursor);
		
		adapter = new SimpleCursorAdapter(this, 
				R.layout.simple_list, 
				cursor, 
				new String[]{"name"}, 
				new int[]{R.id.simple_list_text});
		setListAdapter(adapter);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.category_tab_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mn_category_add:
			showAddCategoryDlg();
			return true;
		case R.id.mn_settings:
			startActivity(new Intent(this, SettingsActivity.class));
//			Toast.makeText(this, "settings selected", Toast.LENGTH_SHORT).show();
			return true;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if(v == getListView()) {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.items_context, menu);
			
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
			Cursor c = (Cursor) adapter.getItem(info.position);
		    menu.setHeaderTitle(c.getString(1));
		}
		super.onCreateContextMenu(menu, v, menuInfo);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
		Cursor c = (Cursor) adapter.getItem(info.position);
		String listItemName = c.getString(1);
		final long id = c.getLong(0);
		
		switch (item.getItemId()) {
		case R.id.men_item_delete:
			Resources res = getResources();
			final Formatter format = new Formatter();
			String message = format.format(res.getString(R.string.msg_sure_to_delete), listItemName).toString();
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(message).setCancelable(false)
			.setPositiveButton(android.R.string.yes, new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					deleteItem(id);
				}
			}).setNegativeButton(android.R.string.no, new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			}).show();
			return true;
		case R.id.men_item_edit:
			new ItemDialog(R.string.dlg_edit_category_title, this, new ItemModel<String>(id, listItemName), catedoryDlgListener).show();
			return true;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}
	
	private void showAddCategoryDlg() {
		if(addCategoryDlg == null) {
			addCategoryDlg = new ItemDialog(R.string.dlg_add_category_title, this, null, catedoryDlgListener);
			
		} else {
			EditText et = (EditText) addCategoryDlg.findViewById(R.id.et_add_simple_item);
			et.setText("");
		}
		
		addCategoryDlg.show();
	}

	public void addItem(ItemModel<String> model) {
		if(model != null
				&& model.getValue() != null
				&& model.getValue().length() > 0) {
			ContentValues values = new ContentValues();
			values.put("name", model.getValue());
			dbProvider.getDatabase(DatabaseMode.Write).insert(Constants.DB_TABLE_CATEGORY, null, values);
			loadData();
		}
	}
	
	public void updateItem(ItemModel<String> model) {
		if(model != null
				&& model.getValue() != null
				&& model.getValue().length() > 0) {
			ContentValues values = new ContentValues();
			values.put("name", model.getValue());
			dbProvider.getDatabase(DatabaseMode.Write).update(Constants.DB_TABLE_CATEGORY, values, "_id=?", new String[]{String.valueOf(model.getId())});
			loadData();
		}
	}
	
	public void deleteItem(Long id) {
		if(id != null) {
			// check if any items are connected to the category
			SQLiteDatabase database = dbProvider.getDatabase(DatabaseMode.Write);
			Cursor c = database.query(Constants.DB_TABLE_MEDIA_ITEM, 
					new String[]{"_id"}, 
					"category_id=?", new String[]{String.valueOf(id)}, 
					null, null, null);
			if(c != null && c.moveToFirst()) {
				c.close();
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage(R.string.msg_err_cannot_delete_category_with_items)
				.setCancelable(false)
				.setPositiveButton(android.R.string.ok, new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				}).show();
			} else {
				database.delete(Constants.DB_TABLE_CATEGORY, "_id=?", new String[]{String.valueOf(id)});
				loadData();
			}
		}
	}
}
